package com.lj.back.manage.scaffold.common.valid;

import com.lj.back.manage.scaffold.common.annotation.valid.EnumCheck;
import com.lj.back.manage.scaffold.common.util.Assert;
import com.lj.back.manage.scaffold.common.util.EnumUtil;
import com.lj.back.manage.scaffold.common.util.EnumValid;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author lv
 * @version 1.0.0
 */
@Slf4j
public class EnumCheckValidator implements ConstraintValidator<EnumCheck,String> {
    private Class<? extends Enum<? extends EnumValid>> enumClass;

    @Override
    public void initialize(EnumCheck enumCheck) {
        enumClass = enumCheck.enumClass();

    }

    @Override
    public boolean isValid(String code, ConstraintValidatorContext context) {
        if (code == null){
            return true;
        }
        Assert.assertNotNull(enumClass,"枚举对象不能为空");
        try {
            return EnumUtil.isValid(enumClass,code);
        } catch (Exception e) {
            log.error("校验枚举参数异常：",e);
        }
        return false;
    }

}
